package com.gdou.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.gdou.commons.Constants;
import com.gdou.commons.Result;
import com.gdou.service.AccountService;
import com.gdou.util.SendEmailUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/*发送邮箱验证码*/
@RestController
@RequestMapping("/email")
public class EmailCodeController {

    @Autowired
    private AccountService accountService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /*  .action*/
    @RequestMapping("/send")
    public Result sendCode(String username,String email){
        Result result = new Result();
        /*1验证 redis中 是否存在可使用的 验证码*/
        String redisKey = Constants.REDIS_EMAIL_KEY+":"+username+":"+email;
        Boolean hasKey = stringRedisTemplate.hasKey(redisKey);
        if (hasKey) {
            result=new Result(-1,"已有验证码，可以继续使用");
            return result;
        }
        /*2验证账号是否存在*/
        boolean hasAccount = accountService.hasAccount(username);
        if (!hasAccount){
            result=new Result(-1,"账号或邮箱错误");
            return result;
        }
        /*3redis不存在  生成验证码          图片  宽  高      验证码位数     干扰元素个数*/
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 50, 6, 10);
        String code = lineCaptcha.getCode();
        /*4发送验证码*/
        try {
            Thread thread = new Thread(new SendEmailUtil(email,code));
            thread.run();
        }catch (Exception e){
            e.printStackTrace();
            return new Result(-1,"邮箱发送失败");
        }
        /*5存入redis  3 分钟过期*/
        stringRedisTemplate.opsForValue().set(redisKey,code);
        stringRedisTemplate.expire(redisKey,3, TimeUnit.MINUTES);
        result=Result.SUCCESS;
        return  result;
    }

}
